import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import store from "@/store"

Vue.use(VueRouter)

const routes = [

  {
    path: '/',
    name: 'home',
    component: Home
  },
  {
    path: '/goods',
    name: 'goods',

    component: () => import('../views/Goods.vue')
  },
  {
    path: '/user',
    name: 'user',
    redirect: '/user/cart',//重定向，默认打开个人中心就显示购物车内容
    component: () => import('../views/User.vue'),
    // 嵌套路由
    children: [
      // 购物车路由
      {
        path: 'cart',
        name: 'cart',
        component: () => import('../components/user/Cart.vue')
      },
    ],


    // 二.路由独享守卫--只有在进入个人中心时才会触发这个钩子函数
    // beforeEnter: (to, from, next) => {
    //   let token = localStorage.getItem('token')
    //   if (token) {
    //     next();
    //   } else {

    //     store.dispatch('showToast/asyncChangeIsShowToast', {
    //       isShow: true,
    //       msg: '请先登录',
    //       type: 'danger'
    //     })
    //     setTimeout(() => {
    //       store.commit('showModal/changeIsShowLoginModal', true)
    //     }, 2000);
    //     return;
    //   }
    // }
    // 三.组件内守卫(书写在组件内)

  },
  {
    path: '/order',
    name: 'order',

    component: () => import('../views/Order.vue')
  },
  {
    path: '/free',
    name: 'free',

    component: () => import('../views/Free.vue')
  },
  {
    path: '/details',
    name: 'details',

    component: () => import('../views/Details.vue')
  }, {
    // 解决404报错，每当上面的路由都不能匹配到，就会匹配到这个路由，跳转到这个页面，显示报错
    path: '/*/',
    name: 'error',
    component: () => import('../components/Error.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 解决重复点击切换路径(路由)报错的问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
}

export default router
